import WebUploader from 'webuploader';

$.initWebUploader = function initWebUploader(param) {

    // 缩略图大小
    let ratio = window.devicePixelRatio || 1
    let thumbnailWidth = 110 * ratio
    let thumbnailHeight = 110 * ratio

    let uploader = WebUploader.create({
        dnd: param.ele,
        paste: document.body,
        disableGlobalDnd: true,

        server: param.url,
        formData: param.formData
    });

    let $filelist = param.ele.find(".filelist");

    $filelist.on("change", "input", function() {
        var file = $(this).val();
        uploader.addFile(file);
    });

    uploader.onFileQueued = function(file) {

        uploader.makeThumb(file, function(error, src) {
            let $li = $(`<li class="file ` + file.id + `">
              <p class="imgWrap">
                  <img src="` + src + `">
              </p>
              <div class="file-panel">
                  <span class="cancel"></span>
                  <span class="title">` + file.name + `</span>
              </div>
            </li>`);

            $li.on("click", ".cancel", function() {
                uploader.removeFile(file, true);
                if ($li.attr("data-id") != undefined) {
                    $.myAjax({
                        url: "ad/delAdFile.do",
                        dataType: "json",
                        contentType: "application/json",
                        data: JSON.stringify({
                            fileId: $li.attr("data-id")
                        }),
                        success: function(result) {
                            $li.off().find('.file-panel').off().end().remove();
                        }
                    });
                } else {
                    $li.off().find('.file-panel').off().end().remove();
                }

            });

            if (error) {
                switch (file.type) {
                    case "text/plain":

                        break;
                    default:

                }

                console.log("不能预览")
                return;
            }

            $filelist.prepend($li);
        }, thumbnailWidth, thumbnailHeight);
    };

    uploader.onUploadSuccess = function(file, res) {
        $filelist.find("." + file.id).attr("data-id", res.data);
    }

    return uploader;
}
